package frontend_gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import java_persistence.*;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JLabel;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import domain.*;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Reader;
import java.util.List;

public class LoginWindow extends JDialog {

	private static final long serialVersionUID = 8818768973372184149L;
	private static Logger log = Logger.getLogger(LoginWindow.class);
	private static SqlSession session = null;
	private final JPanel contentPanel = new JPanel();
	private JTextField textField;
	private JPasswordField passwordField;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {

			//setup the database.
			String myBatis_config = "resources/mybatis-config.xml";
			Reader config_reader = Resources.getResourceAsReader(myBatis_config);
			SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(config_reader);
			session = sessionFactory.openSession();
			
			LoginWindow dialog = new LoginWindow();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			log.info( "Exception caught: " + e.getMessage(), e);
		} finally {
			// it just goes here.  there's a problem with the flow, so we can't close the session????
			//session.close();
		}
		
	}

	/**
	 * Create the dialog.
	 */
	public LoginWindow() {
		setTitle("Welcome");
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		
		textField = new JTextField();
		textField.setBounds(188, 140, 194, 28);
		contentPanel.add(textField);
		textField.setColumns(10);
		
		passwordField = new JPasswordField();
		passwordField.setBounds(188, 180, 194, 28);
		contentPanel.add(passwordField);
		
		JLabel lblUsername = new JLabel("Username");
		lblUsername.setBounds(47, 146, 129, 16);
		contentPanel.add(lblUsername);
		
		JLabel lblNewLabel = new JLabel("Password");
		lblNewLabel.setBounds(47, 186, 129, 16);
		contentPanel.add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("Welcome to DERP by Sciuug-Faults.\nPlease login.");
		lblNewLabel_1.setBounds(47, 6, 335, 122);
		contentPanel.add(lblNewLabel_1);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("Login");
				okButton.addMouseListener(new MouseAdapter() {
					@SuppressWarnings("deprecation")
					@Override
					public void mouseClicked(MouseEvent arg0) {
						System.out.println("OK even caught");
						String db_pass = session.getMapper(UserMapper.class).get_password_by_username(textField.getText());
						if( db_pass.equals(passwordField.getText()) ) {
							System.out.println("valid login");
							setVisible(false);
							main_window( session.getMapper(UserMapper.class).get_user_by_username(textField.getText()) );
						}
						else{
							//dialog - invalid login.
						}
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						setVisible(false);
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
			{
				JButton btnNewButton = new JButton("Register");
				btnNewButton.addMouseListener(new MouseAdapter() {
					@SuppressWarnings("deprecation")
					@Override
					public void mouseClicked(MouseEvent arg0) {
						register_user(textField.getText(), passwordField.getText());
					}
				});
				buttonPane.add(btnNewButton);
			}
		}
	}
	
	private void main_window( User cur_user ) {
		// make the main window
		System.out.println("User " + cur_user.getName() + " logged in.");
		
		boolean patient = true;
		List<Doctor> doctors = session.getMapper(DoctorMapper.class).get_doctors();
		List<Nurse> nurses = session.getMapper(NurseMapper.class).get_nurses();
		List<SystemAdministrator> sas = session.getMapper(SystemAdministratorMapper.class).get_sysadmins();

		/*
		System.out.println("Doctors: " + ((Integer)doctors.size()).toString() );
		System.out.println("Nurses: " + ((Integer)nurses.size()).toString() );
		System.out.println("sas: " + ((Integer)sas.size()).toString() );
		*/
		
		/*if( doctors.contains(cur_user) ){
			System.out.println("user is a doctor");
			// Doctor Window
		}
		else if( nurses.contains(cur_user)) {
			System.out.println("user is a nurse");
			//Nurse Window
		}
		else if( sas.contains(cur_user)) {
			System.out.println("user is a sysadmin");
			//SysAdmin window
		}
		else { //assume patient.
			System.out.println("user is assumed to be a patient");
			//Patient cur_patient = session.getMapper(PatientMapper.class).get_patient_by_username(cur_user.getUsername());
			//patient window (cur_patient)
		}
		*/
		
		for( User i: doctors) {
			if( i.getUsername().equals(cur_user.getUsername())) {
				System.out.println("is a doctor");
				patient = false;
				
				// Doctor Window
			}
		}
		
		
		for( User i: nurses) {
			if( i.getUsername().equals(cur_user.getUsername())) {
				System.out.println("is a nurse");
				patient = false;
				
				// Nurse Window
			}
		}
		
		for( User i: sas) {
			if( i.getUsername().equals(cur_user.getUsername())) {
				System.out.println("is a sysadmin");
				patient = false;
				
				// SysAdmin Window
			}
		}
		
		if ( patient ) {
			System.out.println("is assumed to be a patient");
			
			// Patient Window
		}
		
		
		
		
	}
	
	private void register_user( String username, String password) {
		System.out.println("register user: " + username + " " + password + ".");
	
		List<User> users = session.getMapper(UserMapper.class).get_users();
		boolean valid=true;
		
		for( User i: users) {
			if( i.getUsername().equals(username)) {
				valid = false;
			}
		}
		
		if( valid ) {
			// valid username
			User new_user = new User();
			new_user.setUsername(username);
			new_user.setPassword(password);
			NewUserRegistration.main( new_user, session);
		}
		else {
			//invalid username
		}
		
		// New User Form.
		
	}
}
